<script setup>
import { reactive, ref } from 'vue';
import router from '@/router';
import login2Api from '@/api/login2_api.js';
import adloginApi from '@/api/adlogin_api.js';
// 引入需要的图标组件
import {
  OfficeBuilding, Menu, HomeFilled, Avatar, Notebook,
  Document, Calendar, User, UserFilled, Lock,
  DocumentChecked, Memo, List, Stamp, SwitchButton,
  Expand, Fold
} from '@element-plus/icons-vue';

// 新增：引入密码重置所需组件和图标
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus';
import { Key } from '@element-plus/icons-vue';

const activeIndex = ref('1')

// 取出当前登录用户的信息
const loginAdmin = ref({
  ad_name: "未登录",
  ad_id: "",
});
getLogin();

// 菜单  用户管理， 分类管理， 商品管理
const menuData = ref([
  {name: '房屋土地管理', icon: OfficeBuilding, children: [
      {name: '土地列表', icon: Menu, path: "/index/land"},
      {name: '房屋列表', icon: HomeFilled, path: "/index/house"},
      {name: '家庭列表', icon: Avatar, path: "/index/family"},

    ]},
  {name: '紧急事务管理', icon: Notebook, children: [
      {name: '突发事件通知表', icon: Document, path: "/index/ee"},
      {name: '居民紧急事务上报表', icon: Calendar, path: "/index/re"},
    ]},
  {name: '居民账号', icon: User, children: [
      {name: '居民账号列表', icon: UserFilled, path: "/index/userlogin"},
      {name: '居民信息表', icon: Document, path: "/index/resident"}
    ]},
  {name: '管理员账号', icon: Avatar, children: [
      {name: '管理员列表', icon: List, path: "/index/adlogin"},
    ]},
  {name: '管理员管理', icon: Lock, children: [
      {name: '补贴福利表', icon: DocumentChecked, path: "/index/subsidy"},
      {name: '公共服务表', icon: Memo, path: "/index/public"},
      {name: '展示表', icon: Stamp, path: "/index/sd"}
    ]},
]);
// ============== 新增：密码重置核心代码 ==============
const resetDialog = ref(false);
const resetForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
});
const resetRules = reactive({
  old_password: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  new_password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirm_password: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, val, cb) => val === resetForm.new_password ? cb() : cb(new Error('两次密码不一致')),
      trigger: 'blur'
    }
  ]
});
const formRef = ref(null);

// 打开重置弹窗
function openResetDialog() {
  resetDialog.value = true;
  resetForm.old_password = '';
  resetForm.new_password = '';
  resetForm.confirm_password = '';
}

// 提交密码重置（修正API调用）
async function submitReset() {
  await formRef.value.validate();
  if (!loginAdmin.value.ad_id) {
    ElMessage.error('未获取到用户信息，请重新登录');
    return;
  }
  try {
    // 修正：使用adloginApi调用reset方法
    await adloginApi.reset({
      old_password: resetForm.old_password,
      new_password: resetForm.new_password,
      user_id: loginAdmin.value.ad_id
    });
    ElMessage.success('密码重置成功，请重新登录');
    resetDialog.value = false;
    logout();
  } catch (err) {
    ElMessage.error(err.response?.data?.msg || '重置失败，请检查原密码是否正确');
  }
}
// ============== 新增：密码重置核心代码结束 ==============

async function getLogin(){
  let token=localStorage.getItem("token");// 获取token
  if(!token){
    await router.push('/login');
  }
  if(!loginAdmin.value){
    await router.push('/login')
  }
  const res=await login2Api.getlogin();// 这里没有处理接口失败的情况
  loginAdmin.value=res;// 如果接口失败，res可能未定义
}
// 用户下拉菜单的点击
function handleSelect(key, keyPath){
  if (key == 'logout'){// 用户退出
    logout();
  }
  else if (key == '1-2') openResetDialog(); // 点击重置密码
}
// 左侧菜单动作
function handleMenu(key){
  if (key){
    router.push(key);
  }
}
// 退出
function logout(){
  // 清除Token
  localStorage.removeItem("token");
  // 跳转到登录
  router.push('/login')
}

// 左侧菜单展开折叠
const isCollapse = ref(false);
</script>
<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-menu :default-active="activeIndex"
                 class="el-menu-demo"
                 mode="horizontal"
                 :ellipsis="false"
                 background-color="#f3f7ff"
                 text-color="#393939"
                 active-text-color="#ffd04b"
                 @select="handleSelect"
        >
          <el-menu-item index="0">
            <img style="height: 80%" src="@/assets/logo.png" alt="易视界" />
            <span style="padding-left: 50px; font-size: 24px; color:darkgreen;">利民宝 居民事务管理系统——管理端</span>
          </el-menu-item>
          <div class="flex-grow" />
          <el-sub-menu index="1">
            <template #title>
              <el-icon><Stamp></Stamp></el-icon>
              {{ loginAdmin?loginAdmin.ad_name:'没登录' }}
            </template>
            <el-menu-item index="1-2"><el-icon><Key /></el-icon>重置密码</el-menu-item>
            <el-menu-item index="logout">退出
              <el-icon><SwitchButton></SwitchButton></el-icon>
            </el-menu-item>
          </el-sub-menu>

        </el-menu>
      </el-header>
      <el-container>
        <el-aside :width="isCollapse ? '64px' : '200px'">
          <div style="height: 60px;line-height: 60px; text-align: right; color: #ffffff; font-size: 20px; margin-right: 24px;">
            <el-icon @click="isCollapse=!isCollapse" class="cursor-pointer">
              <Expand v-if="isCollapse"></Expand>
              <Fold v-else></Fold>
            </el-icon>
          </div>
          <el-menu active-text-color="#ffd04b" background-color="#41782C" class="el-menu-vertical-demo"
                   default-active="/charts" text-color="#fff" :collapse="isCollapse"
                   @select="handleMenu">
            <!-- 动态生成菜单 -->
            <el-sub-menu v-for="(menu, index) in menuData" :index="index.toString()">
              <template #title>
                <el-icon>
                  <component :is="menu.icon" />
                </el-icon>
                <span>{{ menu.name }}</span>
              </template>
              <el-menu-item v-for="(child, ind) in menu.children" :index="child.path" :key="ind">
                <el-icon><component :is="child.icon" /></el-icon>
                <span>{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>

          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
    <!-- 新增：密码重置弹窗 -->
    <el-dialog title="重置密码" v-model="resetDialog" width="400px">
      <el-form ref="formRef" :model="resetForm" :rules="resetRules" label-width="100px">
        <el-form-item label="原密码" prop="old_password">
          <el-input v-model="resetForm.old_password" type="password" />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="resetForm.new_password" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input v-model="resetForm.confirm_password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReset">确认重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<style>
/* 确保html和body占据全屏 */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

/* 应用全局样式 */
#app {
  height: 100%;
}

.flex-grow {
  flex-grow: 1;
}

.common-layout,
.el-container {
  height: 100%;
}

.el-header {
  --el-header-padding: 0;
  --el-header-height: 80px;
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  padding: var(--el-header-padding);
}

.el-menu--horizontal {
  height: 80px;
}

.el-aside {
  background-color: #41782C;
  transition: width 0.3s ease; /* 平滑过渡效果 */
}



.el-menu {
  border-width: 0px;
}

.el-menu-item {
  font-size: 16px;
}

.el-menu-demo {
  box-shadow: 0 2px 4px rgba(0,0,0,0.25);
}

.el-sub-menu__title {
  font-size: 16px;
}

.cursor-pointer {
  cursor: pointer;
}
</style>
